package com.coolwen.controller;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.coolwen.entity.User;
import com.coolwen.service.UserService;
import com.coolwen.util.PagedResult;

import java.io.File;
import java.io.IOException;

/**
 * 功能概要：UserController
 *
 * @author
 * @since 2015年9月28日
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    private Logger logger = Logger.getLogger(getClass());

    @Resource
    private UserService userService;

//    @RequestMapping("/")
//    public ModelAndView getIndex() {
//        ModelAndView mav = new ModelAndView("index");
//        User user = userService.selectByPrimaryKey(1);
//        mav.addObject("user", user);
//        return mav;
//    }

    /**
     * 显示首页
     *
     * @return
     * @author linbingwen
     * @since 2015年10月23日
     */
    @RequestMapping("/bootstrapTest1")
    public String bootStrapTest1() {
        return "user/bootstrapTest1";
    }

    /**
     * 分页查询用户信息,使用POST，无法单独在浏览器使用该action
     *
     * @param
     * @return
     * @author linbingwen
     * @since 2015年10月23日
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public String list(Integer pageNumber, Integer pageSize, String userName) {
        logger.info("分页查询用户信息列表请求入参：" + "pageNumber:" + pageNumber + "pageSize:" + pageSize);
        try {
            PagedResult<User> pageResult = userService.queryByPage(userName, pageNumber, pageSize);
            return responseSuccess(pageResult);
        } catch (Exception e) {
            return responseFail(e.getMessage());
        }
    }


    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
        model.addAttribute(new User());
        return "/user/add";

    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(@Validated User user, BindingResult br, @RequestParam("attachs") MultipartFile[] attachs, HttpServletRequest req) {
        if (br.hasErrors()) {
            //如果有错误直接跳转到add视图
            return "/user/add";
        }
        String realPath = req.getSession().getServletContext().getRealPath("/resources/upload");
//        System.out.print(realPath);
        for (MultipartFile attach : attachs) {
            if (attach.isEmpty())
                continue;
            File f = new File(realPath + "/" + attach.getOriginalFilename());
            try {
                FileUtils.copyInputStreamToFile(attach.getInputStream(), f);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        userService.insertSelective(user);
        return "redirect:/user/bootstrapTest1";
    }

    @RequestMapping(value = "/{userId}/update", method = RequestMethod.GET)
    public String update(@PathVariable Integer userId, Model model) {
        User u = userService.selectByPrimaryKey(userId);
        //       System.out.print(u.getUserName());
        model.addAttribute("user", u);
        return "/user/update";
    }

    @RequestMapping(value = "/{userId}/update", method = RequestMethod.POST)
    public String update(@Validated User user, BindingResult br) {
        if (br.hasErrors()) {
            return "/user/update";
        }
        userService.updateByPrimaryKeySelective(user);
        return "redirect:/user/bootstrapTest1";
    }

    @RequestMapping(value = "/{userId}/delete", method = RequestMethod.GET)
    public String delete(@PathVariable Integer userId) {
        User u = userService.selectByPrimaryKey(userId);
        System.out.print(u.getUserName());
        userService.deleteByPrimaryKey(userId);
        return "redirect:/user/bootstrapTest1";
    }
}
